<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="年级" prop="levelName">
        <el-input
          v-model="queryParams.levelName"
          placeholder="请输入年级"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学科" prop="eduName">
        <el-select v-model="queryParams.eduName" placeholder="请选择学科" clearable size="small">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="试题类型" prop="questionType">
        <el-select v-model="queryParams.questionType" placeholder="请选择试题类型" clearable size="small">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="章节" prop="chapter">
        <el-select v-model="queryParams.chapter" placeholder="请选择章节"
                   clearable
                   size="small"
                   @keyup.enter.native="handleQuery"
        >
          <el-option :label="'第'+item+'章'" :value="item" :key="item" v-for="item in chapters" />
        </el-select>
      </el-form-item>
      <el-form-item label="节数" prop="festival">
        <el-select v-model="queryParams.festival" placeholder="请选择节数"   clearable
                   size="small"
                   @keyup.enter.native="handleQuery">
          <el-option :label="'第'+item+'节'" :value="item" :key="item" v-for="item in chapters" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['exam:questions:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['exam:questions:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['exam:questions:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['exam:questions:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="questionsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="年级" align="center" prop="levelName">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.exam_edu" :value="scope.row.levelName"/>
        </template>
      </el-table-column>
      <el-table-column label="学科" align="center" prop="eduName" >
        <template slot-scope="scope">
           {{subjectMap[scope.row.eduName]}}
        </template>
      </el-table-column>
      <el-table-column label="试题类型" align="center" prop="questionType" >
        <template slot-scope="scope">
          {{questionTypeMap[scope.row.questionType]}}
        </template>

      </el-table-column>>
      <el-table-column label="章节" align="center" prop="chapter" />
      <el-table-column label="节数" align="center" prop="festival" />
      <el-table-column label="试题内容" align="center" prop="content" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['exam:questions:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['exam:questions:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改试题管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="false" :center="true" >
      <el-row>
        <el-col :offset="2" :span="18">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">

            <el-form-item label="年级" prop="levelName">
              <el-select v-model="form.levelName" placeholder="请选择年级" @change="levelNameChange" clearable size="small">
                <el-option
                  v-for="dict in dict.type.exam_edu"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="学科" prop="eduName">
              <el-select v-model="form.eduName" placeholder="请选择学科">
                <el-option :label="item.eduName" :value="item.id" :key="item.id" v-for="item in subjectDict"/>
              </el-select>
            </el-form-item>
            <el-form-item label="试题类型" prop="questionType">
              <el-select v-model="form.questionType" placeholder="请选择试题类型">
                <el-option :label="item.name" :value="item.id" :key="item.id" v-for="item in questionTypeDict"/>
              </el-select>
            </el-form-item>
            <el-form-item label="章节" prop="chapter">
              <el-select v-model="form.chapter" placeholder="请选择章节">
                <el-option :label="'第'+item+'章'" :value="''+item" :key="item" v-for="item in chapters" />
              </el-select>
            </el-form-item>
            <el-form-item label="节数" prop="festival">
              <el-select v-model="form.festival" placeholder="请选择节数">
                <el-option :label="'第'+item+'节'" :value="''+item" :key="item" v-for="item in chapters" />
              </el-select>
            </el-form-item>
            <el-form-item label="题干：" prop="wordPath">
              <FileUpload
                :key="open"
                :isMutations="true"
                uploadUrl="/exam/questions/upload"
                :limit="1"
                :fileType="['doc','docx']"
                @upload-success="uploadSuccess"
              ></FileUpload>
              <div slot="tip" class="el-upload__tip" style="color:#f56c6c;">只能上传word文件</div>
            </el-form-item>
            <el-form-item :label="'试题'+(index+1)" v-for="(item,index) in form.questionsList" :key="item.filePath">
              <el-row  type="flex" align="middle" :gutter="15">
                <el-col :span="21">
                  <el-input :value="item.content" :rows="4"  suffix-icon="el-icon-date" disabled type="textarea" placeholder="请输入内容" />
                </el-col>
                <el-col :span="3">
                  <el-button type="danger" icon="el-icon-close" @click="delQuestion(index)"></el-button>
                </el-col>
              </el-row>

            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listQuestions, getQuestions, delQuestions, addQuestions,addQuestionsAll, updateQuestions, exportQuestions } from "@/api/exam/questions";
import { listSubjectAll } from "@/api/exam/subject";
import { listType } from "@/api/exam/type";
import {mapState} from "vuex";


export default {
  name: "Questions",
  dicts: ['exam_edu'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 试题管理表格数据
      questionsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        levelName: null,
        eduName: null,
        questionType: null,
        chapter: null,
        festival: null,
        content: null,
      },
      subjectDict:[], // 学历
      subjectMap:{}, // 学历映射
      questionTypeDict:[], // 试题类型
      questionTypeMap:{}, // 学历映射
      fileList:[], // 文件列表
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        levelName: [
          { required: true, message: "年级不能为空", trigger: "blur" }
        ],
        eduName: [
          { required: true, message: "学科不能为空", trigger: "change" }
        ],
        questionType: [
          { required: true, message: "试题类型不能为空", trigger: "change" }
        ],
        chapter: [
          { required: true, message: "章节不能为空", trigger: "blur" }
        ],
        festival: [
          { required: true, message: "节数不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "试题内容 模糊搜索使用不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    // 试题类型
    listType({
      pageNum: 1,
      pageSize: 100}).then(res=>{
        const questionTypeMap = {}
      this.questionTypeDict = res.rows;
      res.rows.forEach(item=>{
        questionTypeMap[item.id] = item.name
      })
      this.questionTypeMap = questionTypeMap;
    })
    // 学科
    listSubjectAll({
      pageNum: 1,
      pageSize: 100}).then(res=>{
        const subjectMap = []
      res.rows.forEach(item=>{
        subjectMap[item.id] = item.eduName
      })
      this.subjectMap = subjectMap
    })
    this.getList();
  },
  computed:{
    ...mapState({
      chapters:state=>state.exam.chapters
    })
  },
  methods: {
    /**
     * 删除其中的试题
     * @param index
     */
    delQuestion(index){
      this.form.questionsList.splice(index,1)
    },
    /**
     * 文件上传成功的回调
     */
    uploadSuccess (res) {
      this.form.questionsList =res.rows
      console.log(this.form);
    },
    /**
     * 根据年级查询学科
     */
    levelNameChange(val){
      this.form.eduName = "";
      listSubjectAll({
        pageNum: 1,
        pageSize: 100,subjectName:val}).then(res=>{
        this.subjectDict = res.rows;
      })
    },
    /** 查询试题管理列表 */
    getList() {
      this.loading = true;
      listQuestions(this.queryParams).then(response => {
        this.questionsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        levelName: null,
        eduName: null,
        questionType: null,
        chapter: null,
        festival: null,
        content: null,
        questionsList:[],
        createTime: null,
        updateTime: null,
        del: null,
        userId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加试题管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getQuestions(id).then(response => {
        var eduName = response.data.eduName
        this.form = response.data;
        this.levelNameChange(this.form.levelName)
        this.form.eduName = eduName
        this.open = true;
        this.title = "修改试题管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateQuestions(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addQuestionsAll(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除试题管理编号为"' + ids + '"的数据项？').then(function() {
        return delQuestions(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal.confirm('是否确认导出所有试题管理数据项？').then(() => {
        this.exportLoading = true;
        return exportQuestions(queryParams);
      }).then(response => {
        this.$download.name(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    }
  }
};
</script>
